﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.EmpbasicService;
using CommunitySystem.KaoHeService;
using CommunitySystem.PublicOfficialSelectionService;
using EHR.Common;

namespace CommunitySystem
{
    public partial class KaoHeControl : UserControl
    {
        private PublicOfficialSelectionServiceClient downLoadClient = new PublicOfficialSelectionServiceClient();
        private EmpbasicService.EmpBasicServiceClient Client = new EmpbasicService.EmpBasicServiceClient();
        public ObservableCollection<EmpbasicService.OrgForHRModel> OrgList =
            new ObservableCollection<EmpbasicService.OrgForHRModel>();
        ObservableCollection<EmpbasicService.OrgForHRModel> forumList = new ObservableCollection<EmpbasicService.OrgForHRModel>();
        private KaoHeService.KaoHeServiceClient client1 = new KaoHeServiceClient();
        public KaoHeControl()
        {
            InitializeComponent();
            ListBoxOfLife.Items.Clear();
            Client.GetDengLuJueSeCompleted += new EventHandler<EmpbasicService.GetDengLuJueSeCompletedEventArgs>(Client_GetDengLuJueSeCompleted);
            Client.GetDengLuJueSeAsync(Session.LoginUser.LoginName);
            Client.GetOrgForHRModelCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelCompletedEventArgs>(Client_GetOrgForHRModelCompleted);
            Client.GetOrgForHRModelbyIDsCompleted += new EventHandler<EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs>(Client_GetOrgForHRModelbyIDsCompleted);
            Client.GetDengLuOrgCompleted+=new EventHandler<GetDengLuOrgCompletedEventArgs>(Client_GetDengLuOrgCompleted);
            client1.InsertKaoHeCompleted += new EventHandler<InsertKaoHeCompletedEventArgs>(client1_InsertKaoHeCompleted);
        }

        #region 获得组织机构树
        void Client_GetOrgForHRModelCompleted(object sender, EmpbasicService.GetOrgForHRModelCompletedEventArgs e)
        {
            OrgList = e.Result;
            forumList.Clear();
            foreach (EmpbasicService.OrgForHRModel i in e.Result)
            {
                forumList.Add(i);
            }
            AddTreeNode("全部单位", null);
        }

        private void AddTreeNode(string type, TreeViewItem treeViewItem)
        {
            List<EmpbasicService.OrgForHRModel> result = (from forumInfo in forumList
                                                          where forumInfo.Type == type
                                                          select forumInfo).ToList<EmpbasicService.OrgForHRModel>();

            if (result.Count > 0)
            {
                foreach (EmpbasicService.OrgForHRModel foruminfo in result)
                {
                    TreeViewItem objTreeNode = new TreeViewItem();

                    //StackPanel sp = new StackPanel();
                    CheckBox cb = new CheckBox();
                    cb.Content = foruminfo.Name;
                    cb.Tag = objTreeNode;
                    cb.DataContext = foruminfo;
                    //sp.Children.Add(cb);
                    cb.Click += new RoutedEventHandler(cb_Checked);
                    objTreeNode.Header = cb;
                    //objTreeNode.Header = foruminfo.Name;
                    //objTreeNode.DataContext = foruminfo;
                    //objTreeNode.Tag = foruminfo.ID;
                    if ((objTreeNode.Header as CheckBox).Content.ToString() == "组织机构") objTreeNode.IsExpanded = true;

                    //此样式将会添加的所有叶子结点上
                    //objTreeNode.ItemContainerStyle = this.Resources["RedItemStyle"] as Style;

                    //添加根节点
                    if (treeViewItem == null)
                    {
                        TreeOfLife.Items.Add(objTreeNode);
                    }
                    else
                    {
                        treeViewItem.Items.Add(objTreeNode);
                    }
                    AddTreeNode(foruminfo.Name, objTreeNode);
                }
            }
        }
        public int orgid { get; set; }
        public List<string> orgids = new List<string>();
        public string type { get; set; }
        void cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            EmpbasicService.OrgForHRModel rm = cb.DataContext as EmpbasicService.OrgForHRModel;
            if (cb.IsChecked == true)
            {
                //if (orgids != null)
                //{
                //orgid = Convert.ToInt32(((EmpbasicService.OrgForHRModel)cb.DataContext).ID);
                //tbTitle.Text = cb.Content.ToString();
                if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                    orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (string.IsNullOrEmpty(ss) || orgids.Contains("79")) ss = "0";
                else ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
                CheckChildItem(cb.Tag as TreeViewItem);
            }
            else
            {
                //if (orgids != null)
                //{
                if (orgids != null)
                {
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                }
                string ss = "";
                foreach (string i in orgids)
                    ss += i + ",";
                if (ss.Length > 1) ss = ss.Substring(0, ss.Length - 1);
                LoadData(ss);
                UnCheckChildItem(cb.Tag as TreeViewItem);
            }
        }

        void CheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = true;
                    if (!orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Add(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    CheckChildItem(tvi);
                }
            }
        }
        void UnCheckChildItem(TreeViewItem item)
        {
            foreach (TreeViewItem tvi in item.Items)
            {
                if (tvi != null)
                {
                    CheckBox cb = tvi.Header as CheckBox;
                    cb.IsChecked = false;
                    if (orgids.Contains(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString()))
                        orgids.Remove(((EmpbasicService.OrgForHRModel)cb.DataContext).ID.ToString());
                    UnCheckChildItem(tvi);
                }
            }
        }
        #endregion
        #region 左右拖动的条
        private GridLength _lastColLeftLength;
        private GridLength _lastColRightLength;
        private void GridSpliteTo_ToLeft(object sender, EventArgs e)
        {
            //已经到最左边，直接返回
            if (colLeft.Width.Value == 0.0)
            {
                return;
            }

            //
            if (colRight.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colLeft.Width = new GridLength(0);
                colRight.Width = new GridLength(150, GridUnitType.Star);
            }
        }

        private void GridSpliteTo_ToRight(object sender, EventArgs e)
        {
            if (colRight.Width.Value == 0)
            {
                return;
            }

            if (colLeft.Width.Value == 0)
            {
                colLeft.Width = _lastColLeftLength;
                colRight.Width = _lastColRightLength;
            }
            else
            {
                _lastColLeftLength = colLeft.Width;
                _lastColRightLength = colRight.Width;

                colRight.Width = new GridLength(0);
                colLeft.Width = new GridLength(300, GridUnitType.Star);
            }
        }
        #endregion
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            orgid = Convert.ToInt32(((OrgForHRModel)(ListBoxOfLife.SelectedItem)).ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        void Client_GetOrgForHRModelbyIDsCompleted(object sender, EmpbasicService.GetOrgForHRModelbyIDsCompletedEventArgs e)
        {
            ListBoxOfLife.ItemsSource = e.Result;
            ListBoxOfLife.SelectedIndex = 0;
            orgid = Convert.ToInt32(e.Result[0].ID);
            orgids.Clear();
            orgids.Add(orgid.ToString());
            LoadData(orgids[0]);
        }

        void Client_GetDengLuJueSeCompleted(object sender, EmpbasicService.GetDengLuJueSeCompletedEventArgs e)
        {
            if (e.Result != "人事干部")
            {
                if (TreeOfLife.ItemsSource != null) TreeOfLife.ItemsSource = null;
                TreeOfLife.Visibility = System.Windows.Visibility.Visible;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Collapsed;
                Client.GetOrgForHRModelAsync(0);
                LoadData("0");
            }
            else
            {
                TreeOfLife.Visibility = System.Windows.Visibility.Collapsed;
                ListBoxOfLife.Visibility = System.Windows.Visibility.Visible;
                Client.GetDengLuOrgAsync(Session.LoginUser.LoginName);
            }
        }
        public String[] Oldorgids;
        void Client_GetDengLuOrgCompleted(object sender, EmpbasicService.GetDengLuOrgCompletedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Result))
            {
                Oldorgids = e.Result.Split(',');
            }
            Client.GetOrgForHRModelbyIDsAsync("(" + e.Result + ")");
        }
        private void NewData_Click(object sender, RoutedEventArgs e)
        {
            var seljw = this.DGRole.SelectedItem as KaoHeService.KaoHeModel;

            //throw new NotImplementedException();
            if (seljw != null)
            {
                KaoHeShangBaoWindow RMWindow = new KaoHeShangBaoWindow(seljw);
                RMWindow.Closed += new EventHandler(RMWindow_Closed);
                RMWindow.Show();

            }
            else SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择要上报的考核！");
        }

        private void NewData_Click1(object sender, RoutedEventArgs e)
        {
            string ss = "";
            foreach (string ii in orgids)
                ss += ii + ",";
            if (string.IsNullOrEmpty(ss)) ss = "0";
            else ss = ss.Substring(0, ss.Length - 1);
            AddKaoHeEmpWindow RMWindow1 = new AddKaoHeEmpWindow(ss);
            RMWindow1.Closed += new EventHandler(RMWindow1_Closed);
            RMWindow1.Show();

        }

        void RMWindow1_Closed(object sender, EventArgs e)
        {
            ObservableCollection<int> ii = new ObservableCollection<int>();
            if (((AddKaoHeEmpWindow)sender).DialogResult == true && ((AddKaoHeEmpWindow)sender).SelectItems != null)
            {
                foreach (var emp in ((AddKaoHeEmpWindow)sender).SelectItems)
                {
                    ii.Add(emp.ID);
                }
            }
            if(ii.Count > 0)
            {
                client1.InsertKaoHeAsync(ii);
            }
        }

        void client1_InsertKaoHeCompleted(object sender, InsertKaoHeCompletedEventArgs e)
        {
            string ss = "";
            foreach (string ii in orgids)
                ss += ii + ",";
            if (string.IsNullOrEmpty(ss)) ss = "0";
            else ss = ss.Substring(0, ss.Length - 1);
            LoadData(ss);
        }
        public void LoadData(string orgids)
        {
            client1.GetKaoHeCompleted -= new EventHandler<GetKaoHeCompletedEventArgs>(client1_GetKaoHeCompleted);
            client1.GetKaoHeCompleted += new EventHandler<GetKaoHeCompletedEventArgs>(client1_GetKaoHeCompleted);
            client1.GetKaoHeAsync(orgids);
        }

        private ObservableCollection<KaoHe_AttatchmentModel> _Attachment =
            new ObservableCollection<KaoHe_AttatchmentModel>();
        void client1_GetKaoHeCompleted(object sender, GetKaoHeCompletedEventArgs e)
        {
            _Attachment.Clear();
            DGRole.ItemsSource = null;
            if (e.Result != null && e.Result.Count > 0)
            {
                for (int i = 0; i < e.Result.Count; i++)
                {
                    e.Result[i].Sec = i + 1;
                    if (e.Result[i].RZQMSJ == null && Convert.ToDateTime(e.Result[i].RZQMSJ) == Convert.ToDateTime("1900-01-01")) e.Result[i].RZQMSJ = null;
                    //_Attachment.Clear();
                    foreach (var item in e.Result[i].Attachment)
                    {
                        if (!_Attachment.Contains(_Attachment.Where(p=>p.realname == item.realname && p.MainID == item.MainID).FirstOrDefault()))
                            _Attachment.Add(item);
                    }

                }
                DGRole.ItemsSource = e.Result;


            }

        }
        private void Init(int id)
        {
            dgwp.Children.Clear();
            HyperlinkButton hb = null;
            foreach (var item in _Attachment.Where(p => p.MainID == id).ToList())
            {
                hb = new HyperlinkButton() { Margin = new Thickness(10, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
                hb.MouseLeftButtonDown += new MouseButtonEventHandler(hb_MouseLeftButtonDown);
                hb.Tag = item;
                hb.Content = item.realname;
                hb.Click += new RoutedEventHandler(hb_Click);
                dgwp.Children.Add(hb);
            }
        }
        private List<byte> fileContent = new List<byte>();
        void hb_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hbtn = sender as HyperlinkButton;

            var attach = hbtn.Tag as KaoHe_AttatchmentModel;

            SilverlightMessageBoxLibrary.CustomMessage cm = new SilverlightMessageBoxLibrary.CustomMessage("确认要下载此方案吗?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
            cm.Show();
            cm.OKButton.Click += (sender1, e1) =>
            {

                string extend = attach.realname.Substring(attach.realname.LastIndexOf('.'));
                var openFile = new SaveFileDialog() { Filter = string.Format("{0}|*.{0}", extend) };
                if (openFile.ShowDialog() == true)
                {
                    fileContent.Clear();
                    downLoadClient.DownLoadFileCompleted -= new EventHandler<PublicOfficialSelectionService.DownLoadFileCompletedEventArgs>(downLoadClient_DownLoadFileCompleted);
                    downLoadClient.DownLoadFileCompleted += new EventHandler<PublicOfficialSelectionService.DownLoadFileCompletedEventArgs>(downLoadClient_DownLoadFileCompleted);

                    downLoadClient.DownLoadFileAsync(new PublicOfficialSelectionService.DownLoadFile() { PathKey = "file", HasFinished = false, Lenght = 1600, FileName = attach.filename, StartPosition = 0 }, openFile.OpenFile());
                }

            };
        }

        void downLoadClient_DownLoadFileCompleted(object sender, PublicOfficialSelectionService.DownLoadFileCompletedEventArgs e)
        {
            var down = e.Result;
            fileContent.AddRange(down.Content);
            if (down.HasFinished == true)
            {
                var stream = e.UserState as Stream;
                stream.Write(fileContent.ToArray(), 0, fileContent.Count);
                stream.Dispose();
                stream.Close();
                SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
            }
            else
            {
                down.StartPosition += down.Lenght;
                downLoadClient.DownLoadFileAsync(down, e.UserState);
            }
        }

        void hb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void RMWindow_Closed(object sender, EventArgs e)
        {
            string ss = "";
            foreach (string ii in orgids)
                ss += ii + ",";
            if (string.IsNullOrEmpty(ss)) ss = "0";
            else ss = ss.Substring(0, ss.Length - 1);
            LoadData(ss);
        }

        private WrapPanel dgwp = null;
        private void DGRole_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            KaoHeModel bindData = (KaoHeModel)e.Row.DataContext;
            dgwp = DGRole.Columns[9].GetCellContent(e.Row).FindName("wp") as WrapPanel;

            Init(bindData.ID);
        }
    }
}
